package com.learn.docker_demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learn.docker_demo.pojo.User;
import com.learn.docker_demo.service.UserService;
import com.learn.docker_demo.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
* @author DJJ_F
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-07-29 19:25:43
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    public static final String CACHE_USER_PREFIX = "user_";
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void addUser(User user) {
        int i = userMapper.insert(user);
        if (i > 0) {
            user = userMapper.selectById(user.getId());
            redisTemplate.opsForValue().set(CACHE_USER_PREFIX + user.getId(), user);
        }
    }

    @Override
    public User getUserById(Integer id) {
        User user = null;
        String key = CACHE_USER_PREFIX + id;
        user = (User) redisTemplate.opsForValue().get(key);
        if(user == null) {
            user = userMapper.selectById(id);
            if(user != null) {
                redisTemplate.opsForValue().set(key, user);
            }
        }
        return user;
    }
}




